package server.model.storeModel;

import org.apache.commons.dbutils.handlers.BeanHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.entity.Store;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StoreInfoModel {
    public Info getStoreInfo(Integer storeId) {
        Info info = null;
        String sql = "select * from store where store_id = ?";

        Store store = DBFactory.getDBDriver().query(sql, new BeanHandler<>(Store.class, DBDriver.getProcess()), storeId);
        if (store == null) info = InfoUtil.getInfo(1, "没有查询到store");
        else info = InfoUtil.getInfo(store);

        return info;
    }

    public Info setStoreInfo(Store store){
        Info info = null;
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("update store set ");

        String storeName = store.getStoreName();
        if (MyUtils.NOTNULL(storeName)) {
            sql.append(" store_name = ?, ");
            params.add(storeName);
        }

        String description = store.getDescription();
        if (MyUtils.NOTNULL(description)) {
            sql.append(" description = ?, ");
            params.add(description);
        }

        Date createtime=store.getStoreCreatetime();
        if (createtime!=null) {
            sql.append(" store_createtime = ?, ");
            params.add(MyUtils.convertDate2String(createtime,"yyyy-MM-dd"));
        }

        String good = store.getGood();
        if (MyUtils.NOTNULL(good)) {
            sql.append(" good = ?, ");
            params.add(good);
        }

        //设置选择条件
        sql.append(" where store_id = ? limit 1 ");
        params.add(store.getStoreId());

        //去除最后一个“,”
        String endSql = sql.deleteCharAt(sql.lastIndexOf(",")).toString();

        //操作数据库影响的行数
        int line = DBFactory.getDBDriver().update(endSql, params.toArray());

        if (line > 0) {
            info = InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }


}
